package com.github.linkoog.model_designer.ide.editer.dbmodel.gutter.action;

import com.github.linkoog.model_designer.ide.editer.common.Column;
import com.github.linkoog.model_designer.ide.editer.common.ColumnVo;
import com.github.linkoog.model_designer.ide.editer.common.TableVo;
import com.github.linkoog.model_designer.ide.editer.dbmodel.DBModelConstants;
import com.github.linkoog.model_designer.utils.YamlReadUtil;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.project.Project;
import com.intellij.psi.util.PsiTreeUtil;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.yaml.psi.*;

import javax.swing.*;
import java.util.List;
import java.util.Map;

public abstract class AbstractTableAction extends AnAction {

    protected YAMLFile yamlFile;
    protected String tableName;

    public AbstractTableAction(@NotNull YAMLFile yamlFile, @NotNull String tableName, @NotNull String text, String description, Icon icon) {
        super(text, description, icon);
        this.yamlFile = yamlFile;
        this.tableName = tableName;
    }

    public TableVo getTableInfo(Project project){
        final YAMLDocument root = yamlFile.getDocuments().get(0);
        if (root == null) {
            return null;
        }

        YAMLMapping rootMapping = PsiTreeUtil.findChildOfType(root, YAMLMapping.class);
        if (rootMapping == null) {
            return null;
        }

        Map<String, ColumnVo> comcolMap = yamlFile.getVirtualFile().getUserData(DBModelConstants.DB_MODEL_COMMOM_COLUMNS_KEY);
        if (comcolMap == null) {
            return null;
        }

        YAMLKeyValue  yamlKeyValue = rootMapping.getKeyValueByKey(tableName);
        if (yamlKeyValue == null || yamlKeyValue.getValue() == null || !(yamlKeyValue.getValue() instanceof YAMLMapping)){
            return null;
        }
        YAMLMapping tableMapping = (YAMLMapping)yamlKeyValue.getValue();


        //未设置列
        YAMLKeyValue columnsKeyValue = tableMapping.getKeyValueByKey("columns");
        if (columnsKeyValue == null || columnsKeyValue.getValue() == null || !(columnsKeyValue.getValue() instanceof YAMLMapping)){
            return null;
        }
        YAMLMapping columnsMapping = (YAMLMapping)columnsKeyValue.getValue();


        TableVo tableVo = new TableVo();
        tableVo.setName(yamlKeyValue.getKeyText());

        //处理表注释
        YAMLKeyValue commentKeyValue = tableMapping.getKeyValueByKey("comment");
        if (commentKeyValue == null || StringUtils.isBlank(commentKeyValue.getValueText())){
            tableVo.setComment("");
        } else {
            tableVo.setComment(commentKeyValue.getValueText());
        }

        List<Column> columns = YamlReadUtil.readTableColumns(comcolMap, columnsMapping);
        tableVo.setColumns(columns);


        return tableVo;
    }

}
